package flex.cc.wechat.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import flex.cc.common.utils.HttpClientUtil;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.wechat.dao.WechatDao;
import flex.cc.wechat.entity.WechatUserEntity;
import flex.cc.wechat.service.WechatService;

@Service("wechatService")
public class WechatServiceImpl extends ServiceImpl<WechatDao, WechatUserEntity> implements WechatService {

	@Autowired
	private WechatDao wechatDao;
    @Autowired
    private DictCodeService dictCodeService;
	
	@Override
	public int saveUser(String userId, String mobile) {
		QueryWrapper<WechatUserEntity> wrapper=new QueryWrapper<>();
		wrapper.eq("user_id", userId);
		WechatUserEntity wechatUser=this.wechatDao.selectOne(wrapper);
		if(null==wechatUser) {
			WechatUserEntity user=new WechatUserEntity();
			user.setUserId(userId);
			user.setMobile(mobile);
			this.wechatDao.insert(user);
		}else {
			wechatUser.setMobile(mobile);
			this.wechatDao.updateById(wechatUser);
		}
		return 1;
	}
	
	@Override
	public WechatUserEntity queryUserMobile(String code,String appid) {
		WechatUserEntity wechatUser=null;
		String userId=this.getOpenId(code,appid);//"123321";
		if(null!=userId) {
			QueryWrapper<WechatUserEntity> wrapper=new QueryWrapper<>();
			wrapper.eq("user_id", userId);
			wechatUser=this.wechatDao.selectOne(wrapper);
			if(null!=wechatUser) {
				wechatUser.setFlag("1");//有记录的手机号
			}else {
				wechatUser=new WechatUserEntity();
				wechatUser.setFlag("2");//没有记录的手机号
			}
		}else {
			wechatUser=new WechatUserEntity();
			wechatUser.setFlag("0");//获取openID异常
		}
		wechatUser.setUserId(userId);
		return wechatUser;
	}
	
	private String getOpenId(String code,String appid) {
		DictCodeEntity secretVo = dictCodeService.searchAllCodeByTypeCode("wechat", appid, 0, null);
		if(null==secretVo) {
			System.out.println("请配置微信公众号secret");
			return null;
		}
		String secret=secretVo.getValue();
		HttpClientUtil httpUtil=HttpClientUtil.getInstance();
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?"
				+ "appid="+appid
				+ "&secret="+secret
				+ "&code="+code
				+ "&grant_type=authorization_code";
		String res=httpUtil.sendHttpGet(url);
		JSONObject json=JSON.parseObject(res);
		String openid=json.getString("openid");
		System.out.println("响应内容："+res);
		System.out.println("OPID："+openid);
		return openid;
	}

}
